package request

import (
	"errors"
	"reflect"
	"net/http"
	"io/ioutil"
)

type RequestData struct {}

func parseInterface(data interface{}) ([]string, []string, error){
	t := reflect.TypeOf(data)
	v := reflect.ValueOf(data)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	if t.Kind() != reflect.Struct {
		return []string{},[]string{}, errors.New("[ change.tm/request ] - data数据格式错误")
	}
	fieldNum := t.NumField()

	fieldName := make([]string,0,fieldNum)
	fieldData := make([]string,0,fieldNum)
	for i:= 0;i<fieldNum;i++ {
		fieldName = append(fieldName,t.Field(i).Name)
		fieldData = append(fieldData,v.Field(i).String())
	}
	return fieldName, fieldData, nil
}

func Get(url string, data interface{}) (string, error) {
	fieldName, fieldData, err := parseInterface(data)
	if err!=nil {
		return "",err
	}


	request := ""
	for i:=0;i<len(fieldName);i++ {
		request += fieldName[i] + "=" + fieldData[i]
		if i!=len(fieldName)-1 {
			request += "&";
		}
	}
	if request!="" {
		request = "?" + request
	}


	response, err := http.Get(url+request)
	if err != nil {
		return "",err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "",err
	}
	return string(body[:]),nil
}

// func Post(url string, data interface{}, headers interface{}) (string, error) {
// 	client := &http.Client{}

//     req, err := http.NewRequest("POST", url, strings.NewReader("name=cjb"))

//     if err != nil {
// 		return "",err
//     }

//     req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

// 	req.Header.Set("Cookie", "name=anny")
	
//     resp, err := client.Do(req)

//     defer resp.Body.Close()

//     body, err := ioutil.ReadAll(resp.Body)

//     if err != nil {

//     }

//     fmt.Println(string(body))
// }